import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { userAPI } from '@/api/api.js'

export const useUserStore = defineStore('user', () => {
    const user = ref(null)
    const token = ref(localStorage.getItem('leancloud_session_token') || '')
    const isLoggedIn = computed(() => !!token.value && !!user.value)

    // 用户注册
    const register = async (userData) => {
        try {
            const result = await userAPI.register(userData)
            if (result && result.sessionToken) {
                token.value = result.sessionToken
                user.value = result
                localStorage.setItem('leancloud_session_token', result.sessionToken)
                localStorage.setItem('leancloud_user', JSON.stringify(result))
                return { success: true, data: result }
            }
        } catch (error) {
            return { success: false, error: error.message || '注册失败' }
        }
    }

    // 用户登录
    const login = async (username, password) => {
        try {
            const result = await userAPI.login(username, password)
            if (result && result.sessionToken) {
                token.value = result.sessionToken
                user.value = result
                localStorage.setItem('leancloud_session_token', result.sessionToken)
                localStorage.setItem('leancloud_user', JSON.stringify(result))
                return { success: true, data: result }
            }
        } catch (error) {
            return { success: false, error: error.message || '登录失败' }
        }
    }

    // 退出登录
    const logout = async () => {
        try {
            if (token.value) {
                await userAPI.logout(token.value)
            }
        } catch (error) {
            console.error('退出登录失败:', error)
        } finally {
            user.value = null
            token.value = ''
            localStorage.removeItem('leancloud_session_token')
            localStorage.removeItem('leancloud_user')
        }
    }

    // 检查登录状态
    const checkAuth = async () => {
        if (token.value) {
            try {
                const result = await userAPI.getCurrentUser(token.value)
                user.value = result
                return true
            } catch (error) {
                // token失效，清除本地存储
                logout()
                return false
            }
        }
        return false
    }

    // 初始化时检查登录状态
    const init = async () => {
        const storedUser = localStorage.getItem('leancloud_user')
        const storedToken = localStorage.getItem('leancloud_session_token')

        if (storedToken) {
            token.value = storedToken
            if (storedUser) {
                try {
                    user.value = JSON.parse(storedUser)
                } catch (error) {
                    console.error('解析用户信息失败:', error)
                    user.value = null
                }
            }
            // 验证token是否有效
            await checkAuth()
        } else {
            // 如果没有token，确保状态正确
            user.value = null
            token.value = ''
        }
    }

    return {
        user,
        token,
        isLoggedIn,
        register,
        login,
        logout,
        checkAuth,
        init,
    }
})
